// 笨方法
var addTwoNumbers = function (l1, l2) {
  // 判断l1或者l2不为空
  // 遍历两个list，如果有一个为空则需要不位
  let total = 0;
  let next1 = 0;
  let result = new ListNode();
  let cur = result;

  while (l1 && l2) {
      total = l1.val + l2.val + next1
      next1 = Math.floor(total / 10)

      cur.next = new ListNode(total % 10)
      l1 = l1.next
      l2 = l2.next
      cur = cur.next
  }
  // 当l1还有值
  while (l1 != null) {
      total = l1.val + next1
      next1 = Math.floor(total / 10)
      cur.next = new ListNode(total % 10)
      l1 = l1.next
      cur = cur.next
  }

  while (l2 != null) {
      total = l2.val + next1
      next1 = Math.floor(total / 10)
      cur.next = new ListNode(total % 10)
      l2 = l2.next
      cur = cur.next
  }
  if (next1 !== 0) {
      cur.next = new ListNode(next1)
  }
  return result.next
};


// 递归实现
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
  let total = l1.val + l2.val;
  let next1 = Math.floor(total / 10);
  let result = new ListNode(total % 10);
  
  console.log(l1,l2,next1)

  if (l1.next != null || l2.next !== null || next1 !== 0) {

      if (l1.next != null) {
          l1 = l1.next
      } else {
          l1 = new ListNode(0)
      }
      if (l2.next != null) {
          l2 = l2.next
      } else {
          l2 = new ListNode(0)
      }
      if(next1 !== 0){
          l2.val = l2.val + next1
      }
    
      result.next = addTwoNumbers(l1, l2)
  }
 
  return result
};